package net.expectx.pay.merchant.tag;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

/**
 * 百度上传文件指令
 *
 * @author lj
 * 2017.12.27
 */
public class WebUploaderTag extends TagSupport {
    private static final String BASE_FILE = "file";

    private static final String DEFAULT_MESSAGE_TIP = "上传图片，支持.jpg、.jpeg、.png格式照片，单张大小不超过2M,不要超过一张";

    private static final String DEFAULT_PICKER_TEXT = "点击上传，或将文件拖拽到此处";

    private static final String DEFAULT_FILE_TYPE = "images";

    private static final String DEFAULT_FILE_CATALOG = "image";

    private static final Integer DEFAULT_IMAGE_WIDTH = 256;
    private static final Integer DEFAULT_IMAGE_HEIGHT = 135;
    private static final String DEFAULT_IMAGE = "http://chiship.oss-cn-shanghai.aliyuncs.com/image/2019042411465591_963.jpg";
    /**
     * 上传组件ID
     * 必填
     */
    private String pickerId;
    /**
     * 信息提示
     * 选填
     */
    private String messageTip;
    /**
     * 上传按钮文字
     * 选填
     */
    private String pickerText;

    /**
     * 是否开启多张上传
     * 选填
     * 默认 false
     */
    private Boolean multiple;

    /**
     * 上传文件类型
     * 选填
     * 默认 images
     */
    private String fileType;

    /**
     * 上传文件保存文件夹
     * 选填
     * 默认Expect-X
     */
    private String fileCatalog;

    /**
     * 是否上传至本地
     * 选填
     * 默认 true
     */
    private Boolean isLocal;

    /**
     * 文件上传云服务
     * 选填
     * 默认alioss
     */
    private String oss;

    /**
     * 文件回显列表
     * 选填
     */
    private String fileList;

    /**
     * 文件大小限制
     * 选填
     * 默认1M
     */
    private Integer sizeLimit;

    /**
     * 回调函数
     * 选填
     */
    private String callback;

    private Integer width;
    private Integer height;

    /**
     * 是否必填项目
     * 选填
     * 默认 true
     */
    private Boolean required;


    @Override
    public int doEndTag() throws JspException {

        HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        StringBuffer buffer = new StringBuffer();
        multiple = (null == multiple ? false : multiple);
        buffer.append("<div class=\"layui-upload\"  >\n");
        required = (null == required ? true : required);
        String requiredS = "";
        if (required) {
            requiredS = "lay-verify=\"required\"";
        }
        if (null == fileList) {
            buffer.append("<input type=\"hidden\" value='" + DEFAULT_IMAGE + "' name=\"" + pickerId + "\" id=\"" + pickerId + "\" " + requiredS + "  class=\"layui-input\">\n");
        } else {
            buffer.append("<input type=\"hidden\" value=\"" + fileList + "\" name=\"" + pickerId + "\" id=\"" + pickerId + "\" " + requiredS + "  class=\"layui-input\">\n");
        }
        if (!multiple) {
            /**
             * 渲染webuploader组件
             */
            buffer.append("<div id=\"" + pickerId + "Btn\">\n" +
                    "                <div class=\"layui-upload-drag\" style=\"border-radius:8px;\">\n" +
                    "                    <i class=\"layui-icon\">\uE67C</i>\n" +
                    "                    <p>" + (null != pickerText ? pickerText : DEFAULT_PICKER_TEXT) + "</p>\n" +
                    "                </div>\n" +
                    "                <div style=\"margin-top: 15px;color: #999\">\n" +
                    "                    格式要求:" + (null != messageTip ? messageTip : DEFAULT_MESSAGE_TIP) + "\n" +
                    "                </div>\n" +
                    "            </div>\n" +
                    "            <div id=\"" + pickerId + "Div\"\n" +
                    "                 style=\"width: " + (width == null ? DEFAULT_IMAGE_WIDTH : width) + "px; height:" + (height == null ? DEFAULT_IMAGE_HEIGHT : height) + "px;padding: 0px;border-radius:8px;display: none;position: relative;overflow-y: hidden\">\n" +
                    "                <img src=\"" + (null != fileList ? fileList : DEFAULT_IMAGE) + "\" style=\"width: 100%;height: 100%;border-radius: 8px;\" id=\"" + pickerId + "Img\">\n" +
                    "                <div style=\"position: absolute;bottom: 0px;width: 100%;color: #fff;cursor: pointer;background-color: #009688;opacity: 0.8;height: 25px;line-height: 25px;\">\n" +
                    "                    <div class=\"layui-row\" style=\"text-align: center\">\n" +
                    "                        <div class=\"layui-col-xs6\">\n" +
                    "                            <a href=\"javascript:void(0)\" onclick=\"" + pickerId + "Remove()\" style=\"color: #fff\">删除</a>\n" +
                    "                        </div>\n" +
                    "                        <div class=\"layui-col-xs6\">\n" +
                    "                            <a href=\"javascript:void(0)\" id='"+pickerId+"Look' data-src='"+(null != fileList ? fileList : DEFAULT_IMAGE)+"'  server='"+basePath+"' onclick=\"" + pickerId + "Look(this)\" style=\"color: #fff\">查看</a>\n" +
                    "                        </div>\n" +
                    "                    </div>\n" +
                    "                </div>\n" +
                    "            </div>");
            buffer.append(webUploaderSingleScript(basePath));
        } else {
            /*多文件*/
            buffer.append("<ul id=\""+pickerId+"FileUl\">\n" +
                    "                    <li style=\"width: 170px;float: left\">\n" +
                    "                        <div style=\"margin: 5px\" id='"+pickerId+"Btn'>\n" +
                    "                            <div class=\"layui-upload-drag\" style=\"border-radius:8px;\">\n" +
                    "                                <i class=\"layui-icon\">\uE67C</i>\n" +
                    "                                <p>" + (null != pickerText ? pickerText : DEFAULT_PICKER_TEXT) + "</p>\n" +
                    "                            </div>\n" +
                    "                        </div>\n" +
                    "                    </li>\n");
            if (fileList.length() > 0) {
                for (String url : fileList.split(";")) {
                    buffer.append("          <li style=\"width: 170px;float: left\">\n" +
                            "                   <div   style=\"height:154px;padding: 0px;border-radius:8px;;position: relative;overflow-y: hidden;margin:5px\">\n" +
                            "                        <img src=\"" + url + "\" style=\"width: 100%;height: 100%;border-radius: 8px;\">\n" +
                            "                            <div style=\"position: absolute;bottom: 0px;width: 100%;color: #fff;cursor: pointer;background-color: #009688;opacity: 0.8;height: 25px;line-height: 25px;\">\n" +
                            "                                <div class=\"layui-row\" style=\"text-align: center\">\n" +
                            "                                    <div class=\"layui-col-xs6\"><a href=\"javascript:void(0)\" onclick=\""+pickerId+"Remove(this,'" + url + "')\" style=\"color: #fff\">删除</a></div>\n" +
                            "                                    <div class=\"layui-col-xs6\"><a href=\"javascript:void(0)\" id='"+pickerId+"Look' data-src='"+url+"' server='"+basePath+"' onclick=\""+pickerId+"Look(this)\" style=\"color: #fff\">查看</a></div>\n" +
                            "                                </div>\n" +
                            "                            </div>\n" +
                            "                        </div>\n" +
                            "                 </li>\n");
                }
            }
            buffer.append("          </ul>\n" +
                    "                <div style=\"clear: both\"></div>\n" +
                    "                <div style=\"margin-top: 15px;color: #999\">格式要求:" + (null != messageTip ? messageTip : DEFAULT_MESSAGE_TIP) + "\n</div>");

            buffer.append(webUploaderMultipleScript(basePath));

        }
        buffer.append("</div>\n");
        JspWriter out = this.pageContext.getOut();
        try {
            out.println(buffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.doEndTag();

    }

    /**
     * 渲染单文件上传组件脚本
     *
     * @param basePath
     * @return
     */
    public String webUploaderSingleScript(String basePath) {
        StringBuffer buffer = new StringBuffer();
        String server = basePath + "manager/file/upload.html?catalog="
                + (null == fileCatalog ? DEFAULT_FILE_CATALOG : fileCatalog) + "&fileType="
                + (null == fileType ? DEFAULT_FILE_TYPE : fileType) + "&sizeLimit=" + (null == sizeLimit ? 2 : sizeLimit);
        isLocal = null == isLocal ? true : isLocal;
        if (!isLocal) {
            server += "&oss=" + (null == oss ? "alioss" : oss);
        }
        buffer.append("\n<script>\n");
        if (fileList.length() > 0) {
            buffer.append("$(\"#" + pickerId + "Btn\").hide();\n");
            buffer.append("$(\"#" + pickerId + "Div\").show();\n");
        }
        buffer.append("layui.use('upload', function() {\n");
        buffer.append("var $ = layui.jquery\n");
        buffer.append(", upload = layui.upload;\n");
        buffer.append("var " + pickerId + "UploaderInst = upload.render({\n" +
                "                        elem: '#" + pickerId + "Btn',\n" +
                "                        accept: '" + fileType + "',\n" +
                "                        size: " + (null == sizeLimit ? 1 * 1024 : sizeLimit * 1024) + ",\n" +
                "                        url: '" + server + "',\n" +
                "                        before: function (obj) {\n" +
                "                            layer.msg('文件上传中...', {\n" +
                "                                icon: 16\n" +
                "                                , shade: 0.01\n" +
                "                            });\n" +
                "                        },\n" +
                "                        done: function (res) {\n" +
                "                            if (res.success) {\n" +
                "                                $(\"#" + pickerId + "Img\").attr(\"src\", res.data.url);\n" +
                "                                $(\"#" + pickerId + "Btn\").hide();\n" +
                "                                $(\"#" + pickerId + "Div\").show();\n" +
                "                                $(\"#" + pickerId + "Look\").attr('data-src',res.data.url);\n" +
                "                                $(\"#" + pickerId + "Look\").attr('server','"+basePath+"');\n" +
                "                                $(\"#" + pickerId + "\").val(res.data.url);\n");
        if (StringUtils.isNotEmpty(callback)) {
            buffer.append(callback + "();\n");
        }
        buffer.append("                  return layer.msg('上传成功');\n" +
                "                            } else {\n" +
                "                                return layer.msg(res.message);\n" +
                "                            }\n" +
                "                        },\n" +
                "                        error: function () {\n" +
                "                            layer.msg(\"上传失败!\");\n" +
                "                        }\n" +
                "                    });\n");
        buffer.append("})\n");
        buffer.append("function " + pickerId + "Remove() {\n" +
                "                    var file = $(\"#" + pickerId + "\").val();\n" +
                "                    layer.confirm('您确定要删除文件吗？一旦删除将无法恢复!', {\n" +
                "                        btn: ['删除', '取消'] //按钮\n" +
                "                    }, function () {\n" +
                "                        $(\"#" + pickerId + "Btn\").show();\n" +
                "                        $(\"#" + pickerId + "Div\").hide();\n" +
                "                        $(\"#" + pickerId + "Img\").attr(\"src\", \"" + DEFAULT_IMAGE + "\");\n" +
                "                        $(\"#" + pickerId + "\").val('');\n" +
                "                        layer.msg('删除成功', {icon: 1});\n" +
                "                    }, function () {\n" +
                "                    });\n" +
                "                }");
        buffer.append("function " + pickerId + "Look(obj) {\n$(obj).showView();" +
                "                }");
        buffer.append("</script>");
        return buffer.toString();
    }

    /**
     * 渲染多文件上传组件脚本
     * @param basePath
     * @return
     */
    public String webUploaderMultipleScript(String basePath) {
        StringBuffer buffer = new StringBuffer();
        String server = basePath + "manager/file/upload.html?catalog="
                + (null == fileCatalog ? DEFAULT_FILE_CATALOG : fileCatalog) + "&fileType="
                + (null == fileType ? DEFAULT_FILE_TYPE : fileType) + "&sizeLimit=" + (null == sizeLimit ? 2 : sizeLimit);
        isLocal = null == isLocal ? true : isLocal;
        if (!isLocal) {
            server += "&oss=" + (null == oss ? "alioss" : oss);
        }
        buffer.append("\n<script>\n");
        String fileListName=pickerId+"FileList";
        if (fileList.length() > 0) {
            buffer.append("var "+fileListName+"='"+fileList+"'.split(\";\");\n");
        }else{
            buffer.append("var "+fileListName+"=[];\n");
        }
        buffer.append("layui.use('upload', function () {\n" +
                "                        var $ = layui.jquery\n" +
                "                            , upload = layui.upload;\n" +
                "                        var "+pickerId+"UploaderInst = upload.render({\n" +
                "                            elem: '#"+pickerId+"Btn',\n" +
                "                            size: "+(null == sizeLimit ? 1 * 1024 : sizeLimit * 1024)+",\n" +
                "                            accept:'"+fileType+"',\n" +
                "                            multiple:true,\n" +
                "                            url: '" + server + "',\n" +
                "                            before: function (obj) {\n" +
                "                                layer.msg('文件上传中...', {\n" +
                "                                    icon: 16\n" +
                "                                    , shade: 0.01\n" +
                "                                });\n" +
                "                            },\n" +
                "                            done: function (res) {\n" +
                "                                if (res.success) {\n" +
                "                                    "+fileListName+".push(res.data.url);\n" +
                "                                    $(\"#"+pickerId+"\").val("+fileListName+".join(\";\"))\n" +
                "                                    var $li=$(\"<li style=\\\"width: 170px;float: left\\\"></li>\");\n" +
                "                                    var $div1=$(\"<div   style=\\\"height:154px;padding: 0px;border-radius:8px;;position: relative;overflow-y: hidden;margin:5px\\\"></div>\");\n" +
                "                                    var $img1=$(\"<img src=\\\"\"+res.data.url+\"\\\" style=\\\"width: 100%;height: 100%;border-radius: 8px;\\\">\");\n" +
                "                                    var $div2=$(\"<div style=\\\"position: absolute;bottom: 0px;width: 100%;color: #fff;cursor: pointer;background-color: #009688;opacity: 0.8;height: 25px;line-height: 25px;\\\"></div>\")\n" +
                "                                    var $div3=$(\"<div class=\\\"layui-row\\\" style=\\\"text-align: center\\\"></div>\");\n" +
                "                                    var $div4=$(\"<div class=\\\"layui-col-xs6\\\"><a href=\\\"javascript:void(0)\\\" onclick=\\\""+pickerId+"Remove(this,'\"+res.data.url+\"')\\\" style=\\\"color: #fff\\\">删除</a></div>\");\n" +
                "                                    var $div5=$(\"<div class=\\\"layui-col-xs6\\\"><a href=\\\"javascript:void(0)\\\" data-src='\"res.data.url\"' server='"+basePath+"' onclick=\\\""+pickerId+"Look(this)\\\" style=\\\"color: #fff\\\">查看</a></div>\");\n" +
                "                                    $div3.append($div4);\n" +
                "                                    $div3.append($div5);\n" +
                "                                    $div2.append($div3);\n" +
                "                                    $div1.append($img1);\n" +
                "                                    $div1.append($div2);\n" +
                "                                    $li.append($div1);\n" +
                "                                    $(\"#"+pickerId+"FileUl\").append($li)\n" +
                "                                    return layer.msg('上传成功');\n" +
                "                                } else {\n" +
                "                                    return layer.msg(res.message);\n" +
                "                                }\n" +
                "                            },\n" +
                "                            error: function () {\n" +
                "                                layer.msg(\"上传失败!\");\n" +
                "                            }\n" +
                "                        });\n" +
                "                    })\n" +
                "                    function "+pickerId+"Remove(obj,url) {\n" +
                "                        layer.confirm('您确定要删除文件吗？一旦删除将无法恢复!', {\n" +
                "                            btn: ['删除', '取消'] //按钮\n" +
                "                        }, function () {\n" +
                "                            var index="+fileListName+".indexOf(url);\n" +
                "                            "+fileListName+".splice(index,1);\n" +
                "                            $(\"#"+pickerId+"\").val("+fileListName+".join(\";\"));\n" +
                "                            $(obj).closest('li').remove()\n" +
                "                            layer.msg('删除成功', {icon: 1});\n" +
                "                        }, function () {\n" +
                "                        });\n" +
                "                    }");
        buffer.append("function " + pickerId + "Look(obj) {\n$(obj).showView();" +
                "                }");
        buffer.append("</script>");
        return buffer.toString();
    }

    public String getMessageTip() {
        return messageTip;

    }

    public void setMessageTip(String messageTip) {

        this.messageTip = messageTip;

    }

    public String getPickerText() {

        return pickerText;

    }

    public void setPickerText(String pickerText) {

        this.pickerText = pickerText;

    }

    public String getPickerId() {

        return pickerId;

    }

    public void setPickerId(String pickerId) {

        this.pickerId = pickerId;

    }

    public Boolean getMultiple() {

        return multiple;

    }

    public void setMultiple(Boolean multiple) {

        this.multiple = multiple;

    }

    public String getFileType() {

        return fileType;

    }

    public void setFileType(String fileType) {

        this.fileType = fileType;

    }

    public String getFileCatalog() {

        return fileCatalog;

    }

    public void setFileCatalog(String fileCatalog) {

        this.fileCatalog = fileCatalog;

    }

    public Boolean getIsLocal() {

        return isLocal;

    }

    public void setIsLocal(Boolean local) {

        isLocal = local;

    }

    public String getOss() {

        return oss;

    }

    public void setOss(String oss) {

        this.oss = oss;

    }

    public static String getDefaultMessageTip() {

        return DEFAULT_MESSAGE_TIP;

    }

    public String getFileList() {

        return fileList;

    }

    public void setFileList(String fileList) {

        this.fileList = fileList;

    }

    public Integer getSizeLimit() {

        return sizeLimit;

    }

    public void setSizeLimit(Integer sizeLimit) {

        this.sizeLimit = sizeLimit;

    }

    public void setCallback(String callback) {
        this.callback = callback;
    }

    public String getCallback() {
        return callback;
    }

    public Integer getWidth() {
        return width;
    }

    public void setWidth(Integer width) {
        this.width = width;
    }

    public Boolean getRequired() {
        return required;
    }

    public void setRequired(Boolean required) {
        this.required = required;
    }

    public Integer getHeight() {
        return height;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }
}
